package com.example.lin.localbroadcastmanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private MyLocalReceiver myLocalReceiver;

    class MyLocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "" + intent.getStringExtra("str"), Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册本地广播
        myLocalReceiver = new MyLocalReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("a.b.c.d");
        LocalBroadcastManager.getInstance(this).registerReceiver(myLocalReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //注销本地广播
        LocalBroadcastManager.getInstance(this).unregisterReceiver(myLocalReceiver);
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        //发送本地广播
        Intent intent = new Intent();
        intent.setAction("a.b.c.d");
        intent.putExtra("str", "哈哈哈哈");
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }


}
